#include <QtGui>

#include "qclickablelabel.h"

//constructor
QClickableLabel::QClickableLabel(QWidget *parent)
         :QLabel(parent)
{
    QWidget::setMouseTracking(true);    
    this->setAlignment(Qt::AlignHCenter);
    this->setAlignment(Qt::AlignCenter);
}

/* This method gets called when the mouse is pressed
 * In turn it emits a clicked signal which will be handled in the main window
 */
void QClickableLabel::mousePressEvent(QMouseEvent *event)
{   
   if(event->button() == Qt::LeftButton) //--- to check which button was pressed
   {
       emit clicked();
   }
}

/* This method gets called when the mouse is double clicked
 * In turn it emits a doubleClicked signal which will be handled in the main window
 */
void QClickableLabel::mouseDoubleClickEvent(QMouseEvent *event)
{   
   if(event->button() == Qt::LeftButton) //--- to check which button was pressed
   {
       emit doubleClicked();
   }
}

void QClickableLabel::resizeEvent(QResizeEvent *event)
{
    // superclass resizes us first
    QLabel::resizeEvent(event);
    // check there is an image to draw
    if(this->pixmap() != 0)
    {
        // record scaled size for painting border
        scaledSize = originalImage.size();
        scaledSize.scale(this->size(), Qt::KeepAspectRatio);
        if(scaledSize != this->pixmap()->size())
        {
            this->setPixmap(originalImage.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        }
    }
}

// draw a border in the paint event
void QClickableLabel::paintEvent(QPaintEvent *event) {
    QLabel::paintEvent(event); // throw to parent
    // paint nice border
    QPainter p(this);
    QSize sizeMinusOne(scaledSize.width()-1,scaledSize.height()-1);
    // find top left corner. QLabel paints image there automatically
    QPoint topLeftPt(   (size().width()-scaledSize.width())>>1,
                        (size().height()-scaledSize.height())>>1    );
    p.drawRect(QRect(topLeftPt,sizeMinusOne));
}

void QClickableLabel::setClickablePixmap(const QPixmap &original)
{
    originalImage = original;
    this->setPixmap(original);
    this->resize(original.size());
    this->resize(this->size());
}



//deconstructor
QClickableLabel::~QClickableLabel()
{
}
